#include "../main.h"

void add_To_KMap(KMap *map, int key)
{
    KNode *node = get_by_key(map, key);
    if (node == NULL)
    {
        KNode *curNode = map->head;
        KNode *lastNode = NULL;
        while (curNode)
        {
            if (curNode->next == NULL)
            {
                lastNode = curNode;
                break;
            }
            curNode = curNode->next;
        }
        if (lastNode == NULL)
        {
            KNode *appendNode = (KNode *)malloc(sizeof(KNode));
            appendNode->next = NULL;
            appendNode->key = key;
            map->head = appendNode;
        }
        else
        {

            KNode *appendNode = (KNode *)malloc(sizeof(KNode));
            appendNode->next = NULL;
            appendNode->key = key;
            lastNode->next = appendNode;
        }
    }
}
KNode *get_by_key(KMap *map, int key)
{
    if (is_keymap_null(map) == 1)
    {
        return NULL;
    }
    KNode *curNode = map->head;
    while (curNode)
    {
        if (key == curNode->key)
        {
            return curNode;
        }
        curNode = curNode->next;
    }
    return NULL;
}
void remove_by_key(KMap *map, int key)
{
    if (is_keymap_null(map))
    {
        return;
    }
    KNode *curNode = map->head;
    while (curNode)
    {
        if (curNode->next != NULL)
        {
            if (key == curNode->next->key)
            {
                KNode *fnode = curNode->next;
                if (curNode->next->next != NULL)
                {
                    curNode->next = curNode->next->next;
                }
                else
                {
                    curNode->next = NULL;
                }
                free(fnode);
                fnode = NULL;
                break;
            }
        }
        else
        {
            KNode *fnode = curNode;
            if (key == curNode->key)
            {
                map->head = curNode->next;
                free(fnode);
                fnode = NULL;
                break;
            }
        }
        curNode = curNode->next;
    }
}
int is_keymap_null(KMap *map)
{
    if (map != NULL)
    {
        if (map->head == NULL)
        {
            return 1;
        }
        if (map->head != NULL)
        {
            return 0;
        }
    }
    return 1;
}